package cn.afactory.tygz.ui.sns.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.model.PicsItem;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.SnsCommentInfo;
import cn.afactory.tygz.model.SnsCommentInfoList;
import cn.afactory.tygz.model.SnsSubjectDetail;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.adapter.CommentListAdapter;
import cn.afactory.tygz.ui.base.adapter.NearByForumsAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.base.views.AutoGridView;
import cn.afactory.tygz.ui.base.views.SubjectDetailHeaderView;
import cn.afactory.tygz.ui.sns.SendCommentActivity;
import cn.afactory.tygz.ui.sns.SubjectDetailActivity;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * Created by Kenneth on 15/9/17.
 */
public class SubjectDetailFragment extends BaseFragment implements NearByForumsAdapter.OnItemClickListener{
    private static final String TAG = SubjectDetailFragment.class.getSimpleName();
    public static final int REQUEST_CODE_COMMENT = 0x1001;
    public static final String EXTRA_DES = "extraDes";

    private CommentListAdapter mAdapter;
    private  List<SnsCommentInfo> listData = new ArrayList<SnsCommentInfo>();
    protected SnsControler mController;
    private SnsSubjectDetail snsSubjectDetail;

    private SubjectDetailHeaderView subjectDetailHeaderView;
    private LayoutInflater minflater;
    private TextView mTvSend;
    public SubjectDetailFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new SnsControler(mContext, mUIHandler, null);
        snsSubjectDetail = (SnsSubjectDetail)getArguments().getSerializable(SubjectDetailActivity.SUBJECT_DETAIL_TAG);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        this.minflater = inflater;
        View mlayout = inflater.inflate(R.layout.fg_subject_detail, null);
        initViews(mlayout);
        showTitleBar(false);
        return mlayout;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_FORUMS_DETAIL_OK:
                if (msg.obj instanceof SnsSubjectDetail) {
                    hideErrorPage(-1);
                    SnsSubjectDetail detail = (SnsSubjectDetail)msg.obj;
                    if (null != detail) {
                        subjectDetailHeaderView.setmSnsSubjectDetail(detail);
                    }
                }
                break;
            case SnsControler.MSG_GET_FORUMS_DETAIL_KO:
                hideErrorPage(-1);
                showErrorPage(msg.arg1, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        startLoadSubjectDetail();
                    }
                });
                break;
            case SnsControler.MSG_GET_FORUMS_COMMENTS_OK:
                if (msg.obj instanceof SnsCommentInfoList) {
                    SnsCommentInfoList snsCommentInfoList = (SnsCommentInfoList)msg.obj;
                    if (null != snsCommentInfoList && null != snsCommentInfoList.userInfoList && snsCommentInfoList.userInfoList.size() > 0) {
                        if (mAdapter.getCount() == 0 && mLastReqTime == 0) {
                            listData.addAll(snsCommentInfoList.userInfoList);
                        } else {
                            if (mLastReqTime == 0) {
                                listData.clear();
                            }
                            listData.addAll(snsCommentInfoList.userInfoList);
                            mLastReqTime = snsCommentInfoList.userInfoList.get(snsCommentInfoList.userInfoList.size() - 1).addTime;
                        }

                        mAdapter.addDataAll(listData);
                        mPageIndex = (listData.size()/mPageSize) + 1;

                        if (plistview.isRefreshing()) {
                            plistview.onRefreshComplete();
                        }
                        if (snsCommentInfoList.userInfoList.size() < mPageSize) {
                            plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        } else {
                            plistview.setMode(PullToRefreshBase.Mode.BOTH);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_FORUMS_COMMENTS_KO:

                break;
            default:
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        startLoadSubjectDetail();
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_subject);
        mTvSend = (TextView) view.findViewById(R.id.tv_send);
        mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TimeUtil.isFastDoubleClick()) {
                    return;
                }
                Intent intent = new Intent(mContext, SendCommentActivity.class);
                intent.putExtra(EXTRA_DES, "评论");
                intent.putExtra(SPUtils.EXTRA_POST_ID, snsSubjectDetail.id);
                startActivityForResult(intent, REQUEST_CODE_COMMENT);
            }
        });
        initListView();
    }

    public void startLoadSubjectDetail() {
        mController.doLoadSubjectDetail(snsSubjectDetail.id);
        startLoadCommentData(true);
    }

    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadCommentData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            listData.clear();
        }
        mController.doLoadSubjectCommentList(snsSubjectDetail.id,mPageIndex, mPageSize);
    }

    /**
     * 初始化list view
     */
    private void initListView() {

        subjectDetailHeaderView = new SubjectDetailHeaderView(mContext, null, snsSubjectDetail);
        subjectDetailHeaderView.setOnItemClickLsn(this);
        plistview.getRefreshableView().addHeaderView(subjectDetailHeaderView, null, false);

        mAdapter = new CommentListAdapter(mContext,null);
        mAdapter.setOnItemClickLsn(this);
        mAdapter.setListType(1);
        plistview.setAdapter(mAdapter);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectDetail();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadCommentData(false);
            }
        });
    }

    protected void setListListener() {

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPraise(TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(v, item);
        }
    }

    @Override
    public void onPraise(AutoGridView autoGridView, TextView v, SnsSubjectDetail item) {

    }

    @Override
    public void onClickImage(int position, List<String> mPath) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (mPath != null) {
            ArrayList<PicsItem> list = new ArrayList<>();
            for (String tmp : mPath) {
                PicsItem picsItem = new PicsItem();
                picsItem.image = ImageUtils.getBigImageFullPath(tmp);
                list.add(picsItem);
            }
            NaviUtils.gotoViewBigImageActivity(getActivity(),list, position, false, false);
        }
    }

    @Override
    public void onClickTopic(String topic, long topicId) {
        NaviUtils.gotoTopicDetailActivity(mContext, topicId);
    }

    @Override
    public void onClickShare(SnsSubjectDetail item) {
        DialogUtil.showShareDialog(getActivity(), "分享Title",
                item.content,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    @Override
    public void onClickIcon(SnsSubjectDetail item) {
        NaviUtils.gotoUserProfileActivity(getActivity(), item.userId, item.nickName);
    }

    @Override
    public void onClickCommentIcon(SnsCommentInfo commentInfo) {
        NaviUtils.gotoUserProfileActivity(getActivity(), commentInfo.userId, commentInfo.userName);
    }

    @Override
    public void onClickTextContent(SnsSubjectDetail item) {

    }

    @Override
    public void onClickSubjectList(String str) {

    }

    @Override
    public void onClickComment(SnsSubjectDetail item) {

    }

    @Override
    public void onClickCompany(SnsSubjectDetail item) {

    }
}

